<?php
namespace app\api\controller;
use app\Response;
use QL\QueryList;
use \Curl\Curl;
use app\api\controller\Rename;
use app\common;
use think\Db;

class Test {
	public function index(){
		//array_rand随机取出数组中的键名
		/*$a=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
		$b = array_rand($a,1);
		var_dump($a[$b]);*/
		//数组差集
		//函数array_diff()返回出现在第一个数组中但其他输入数组中没有的值。
		/*$fruit1 = array("Apple","Banana","Orange");
		$fruit2 = array("Pear","Apple","Grape");
		$fruit3 = array("Watermelon","Orange","Apple");
		$fruit4 = array("Apple","Banana","Orange");
		$intersection = array_diff($fruit1, $fruit4);
		print_r($intersection);*/
		//php获取一维数组里面的最小值：
		/*$a=array('4','3','55','99');
		$b = array("a"=>"5","b"=>"4","c"=>"2","d"=>"9","e"=>"2");
		$pos=array_search(min($b),$b);
		//echo $b[$pos];
		var_dump(min($b),$pos);die;*/
/*
		$url1 = "http://static.anoah.com/uploads//uploadcover/6c/7b/1097877.jpg";
		$url2 = "/uploads/cover/temp_pic/890e89bb06202bbbc2ed341c8ec6ba8a.png";

		$arr1 = explode('/uploads/', $url1);
		$arr2 = explode('/uploads/', $url2);
		
		$pic1 = isset($arr1[1])?'/uploads/'.ltrim($arr1[1], '/'):'';
		$pic2 = isset($arr2[1])?'/uploads/'.ltrim($arr2[1], '/'):'';

		$a = stristr($url1, 'uploadcover');
		$b = stristr($url2, 'uploadcover');

		var_dump($pic1, $pic2, $a, $b);
		die;*/

		/*$path = "../../uploads/img/4.jpg";
		$file = file_exists($path);
		var_dump($file);
		die;
		$php = phpinfo();
		echo $php;*/

		$number = 110;
		$result = Rename::numberToChapter($number);
		var_dump($result);
	}
	public function download(){
		$ext = '.jpg';
		$filename = isset($_GET['filename'])?$_GET['filename']:'美图';
		$filename = $filename.$ext;
		
		$filepath = rand(1,3);
		$filepath = $filepath.$ext;

		//var_dump($filename, $filepath);die;

		header("Content-Disposition: attachment; filename= '{$filename}'");

		header("Content-Type: application/octet-stream");

		header('X-Accel-Redirect: /uploads/img/'.$filepath); 
	}

	public function webdownload(){
		//http://e.dev.anoah.com/uploads/class/2b/2f/1100653.jpg
		$ext = '.jpg';
		$filename = isset($_GET['filename'])?$_GET['filename']:'美图';
		$filename = $filename.$ext;
		
		//$filepath = rand(1,3);
		//$filepath = $filepath.$ext;
		$filepath = '/uploads/class/2b/2f/1100653.jpg';

		//var_dump($filename, $filepath);die;

		header("Content-Disposition: attachment; filename= '{$filename}'");

		header("Content-Type: application/octet-stream");

		header('X-Accel-Redirect: /protected_files'.$filepath); 
	}

	public function file_exists()
	{
		$url = isset($_GET['url'])?$_GET['url']:'http://e.anoah.com/uploads/uploadcover/0a/d0/1107183.jpg';

		$filesize = @getimagesize($url);

		var_dump($filesize);die;

		$ch = curl_init();
		curl_setopt($ch, curlopt_url,$url);
		curl_setopt($ch, curlopt_nobody, 1); // 不下载
		curl_setopt($ch, curlopt_failonerror, 1);
		curl_setopt($ch, curlopt_returntransfer, 1);

		if(curl_exec($ch)!==false)
		return true;
		else
		return false;
	}

	/**
	 * [testImg 测试图片是否存在]
	 * @return [type] [description]
	 * 通过http状态码来判断文件是否存在，比如，响应 302,301,404等都为不存在，如果是200，304，等可以视为文件存在。
	 */
	public function testImg(){
		//$url = "http://www.baidu.com/img/baidu_sylogo1.gif";
		//$url = "http://qres1.noahedu.com/2/33/7/140117/小学数学知识点库20140114/数学多媒体关系表/视频搜索缩略图/名师点拨04(870X490).png";
		//$url = "http://e.dev.anoah.com/uploads/cover/temp_pic/ed3293dbf45cf9174c30243ebe90854a.jpg";
		$url = "http://me.com/api/test/webdownload";
		//
		$file = self::check_remote_file_exists($url);
		var_dump($file);die;

		/*$ui = self::DoGet($url);
		var_dump($ui);die;*/

	    $info = parse_url($url);
	    $fsock_timeout = 1000;
	    $fsock = fsockopen($info['host'], 80,$errno, $errstr, $fsock_timeout);
	    fputs($fsock,"GET {$info['path']} HTTP/1.1\r\n");
	    fputs($fsock, "Host: {$info['host']}\r\n");
	    fputs($fsock, "Connection: close\r\n\r\n");

	   /* stream_set_timeout( $fsock , $fsock_timeout );
	    $status = stream_get_meta_data( $fsock );*/
	    //读取数据超时
	    /*if( $status['timed_out'] )
	    {
	        echo "Read time out" ;
	        fclose( $fsock );
	        return false;
	    }*/
	    
	    $headers = array();

	    while(!feof($fsock)) {
	    	$line = fgets($fsock);
		    if($line != "\r\n") {
		    	$headers[] = $line;
		    }else {
		    	break;
		    }
	    }

	    echo "<pre>";
	    print_r($headers);

	    $status = isset($headers[0])?$headers[0]:'';
var_dump($status);die;
	    if ($status && (preg_match("/200/", $status) || preg_match("/304/", $status))){
        	echo '文件存在';
    	}else{
    		echo '文件不存在';
    	}
	}

	public static function check_remote_file_exists($url) {
		//set_time_limit(30); //单位秒
	    $curl = curl_init($url);
	    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30); //连接时间
	    //不取回数据
	    curl_setopt($curl, CURLOPT_NOBODY, true);
	    curl_setopt($curl, CURLOPT_TIMEOUT, 5);//30秒
	    curl_setopt($curl, CURLOPT_HEADER, true);  
	    //发送请求
	    $response = curl_exec($curl);
	    $found = false;
	    if($response !== false){
	        //检查http响应码是否为200
	        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);  
	        if ($statusCode == 200) {
	            $found = true;   
	        }
	    }else if(curl_errno($curl) == CURLE_OPERATION_TIMEDOUT){
	    	echo "超时";
	    }
	    curl_close($curl);
	    return $found;
	}

	public static function DoGet($url)
	{
		$url2 = parse_url($url);
		if(!isset($url2['path']))$url2['path']='';
		$url2['path'] = ($url2['path'] == '' ? '/':$url2['path']);
		$url2['port'] = (isset($url2['port']) ? $url2['port']:80);
		$host_ip = @gethostbyname($url2['host']);
		$fsock_timeout = 30; //2 second
		if(!($fsock = fsockopen($host_ip, $url2['port'], $errno, $errstr, $fsock_timeout)))
		{
			echo 'fsockopen fail';
			return false;
		}
		$request = $url2["path"].(isset($url2["query"]) ? "?".$url2["query"] : "");
		$in = "GET " . $request . " HTTP/1.0\r\n";
		$in .= "Accept: */*\r\n";
		$in .= "User-Agent: Payb-Agent\r\n";
		$in .= "Host: " . $url2["host"] . "\r\n";
		$in .= "Connection: Close\r\n\r\n";
		
		stream_set_timeout($fsock , $fsock_timeout);
		if(!@fwrite($fsock, $in, strlen($in))){
			echo 'fwrite fail';
			fclose($fsock);
			return false;
		}
		$status = stream_get_meta_data($fsock);
		//发送数据超时
		if($status['timed_out'])
		{
			echo "Write time out";
			fclose($fsock);
			return false;
		}
		$out = null;
		while($buff = @fgets($fsock, 2048))
		{
			$out .= $buff;
			//只读取头部信息
			if(false!==strpos($out, "\r\n\r\n"))break;
		}
		$status = stream_get_meta_data($fsock);
		//读取数据超时
		if($status['timed_out'])
		{
			echo "Read time out";
			fclose($fsock);
			return false;
		}
		fclose($fsock);

		$pos = strpos($out, "\r\n\r\n");
		$head = substr($out, 0, $pos);  //http head
		return $head;
	}

	/**
	 * [encoding 编码转化]
	 * @param  string $str           [要转化的字符]
	 * @param  string $encoding_to   [要转化的目的编码]
	 * @param  string $encoding_from [原编码]
	 * @return [type]                [description]
	 */
	public static function encoding($str='', $encoding_to="UTF-8", $encoding_from="GBK"){
		if($str){
			//已知原编码为encoding_from，转换为encoding_to
			$str = mb_convert_encoding($str, $encoding_to, $encoding_from); 
		}
		return $str;
	}
}